//
//  NetworkTools.swift
//  TYHWeibo
//
//  Created by IOS on 15/7/31.
//  Copyright © 2015年 IOS. All rights reserved.
//

import UIKit
import AFNetworking

private let TYHErrorDomainName = "com.error.network"

///网络访问信息 - 枚举, 是定义一组类似的值
private enum TYHNetworkError: Int {
    case emptyDataError = -1
    case emptyTokenError = -2
    
    ///错误描述
    private var errorDescrption: String {
        switch self {
        case .emptyDataError: return "空数据"
        case.emptyTokenError: return "Token 为空"
            
        }
        
    }
    ///根据枚举返回对应的错误
    private func error() -> NSError {
        return NSError(domain: TYHErrorDomainName, code: rawValue, userInfo: [TYHErrorDomainName: errorDescrption])
    }

}

///网络访问方法
private enum TYHNetworkMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    //网络回调类型别名
    typealias TYHNetFinishCallBack = (result: [String: AnyObject]?, error:
        NSError?) -> ()
    
    //应用程序信息
    private let clientId = "277607315"
    private let appSecret = "3c32c79f23393343df07aa1bffa46c80"
    //回调地址
    let redirectUri = "http://www.baidu.com"
    
    //单例
    static let sharedTools: NetworkTools = {
        let baseURL = NSURL(string: "https://api.weibo.com/")!
        let tools = NetworkTools(baseURL: baseURL)
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        
        return tools
    }()
    
    ///检查并生成token
    private func tokenDict(finished: TYHNetFinishCallBack) -> [String: AnyObject]? {
        //判断是否存在
        if UserAccount.sharedAccount?.access_token == nil {
            let error = TYHNetworkError.emptyTokenError.error()
            print(error)
            finished(result: nil, error: error)
            return nil
        }
        
        return ["access_token": UserAccount.sharedAccount!.access_token!]
        
    }
    
    //发送微博
    func sendStatus(status: String, image: UIImage?, finished: TYHNetFinishCallBack) {
        guard var params = tokenDict(finished) else {
            // params 在此为 nil，一般直接返回
            // 提示：tokenDict已经做了token为空的错误回调
            return
        }
        
        params["status"] = status
        
        if image == nil {
        request(TYHNetworkMethod.POST, urlString: "2/statuses/update.json", params: params, finished: finished)
        } else {
            
            uploadImage("https://upload.api.weibo.com/2/statuses/upload.json", image: image!, params: params, finished: finished)
        }
        
    
    }
    
    //MARK: 加载微博数据
    func loadStatus(since_id: Int, max_id: Int, finished: TYHNetFinishCallBack) {
        
        // 判断 token 是否存在，为 nil 直接返回
        // guard 是 swift 2.0 的新语法，跟 if let 刚好相反
        // let 获得的变量，后续可以直接使用，而且一定不为 nil
        guard var params = tokenDict(finished) else {
            // params 在此为 nil，一般直接返回
            // 提示：tokenDict已经做了token为空的错误回调
            return
        }
        
        if since_id > 0 {
            params["since_id"] = since_id
        }
        if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        
        let urlString = "2/statuses/home_timeline.json"
        
        request(TYHNetworkMethod.GET, urlString: urlString, params: params, finished: finished)

        
    }
    
    //MARK: 加载用户数据
    func loadUserInfo(uid: String, finished: TYHNetFinishCallBack) {
        
        let urlString = "2/users/show.json"
        guard var params = tokenDict(finished) else {
            return
        }
        
        params["uid"] = uid
//        requestGET(urlString, params: params, finished: finished)
        request(TYHNetworkMethod.GET, urlString: urlString, params: params, finished: finished)
        
    }
    
    //MARK: OAuth授权
    
    //返回OAuth的授权地址
    func oauthUrl() -> NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    
    ///加载token
    func loadAccessToken(code: NSString,finished: TYHNetFinishCallBack) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code, 
            "redirect_uri": redirectUri]
//        responseSerializer = AFHTTPResponseSerializer()
        
        
        request(TYHNetworkMethod.POST, urlString: urlString, params: params, finished: finished)
        
//        POST(urlString, parameters: params, success: { (_, JSON) -> Void in
////                print(JSON)
////            print(NSString(data: JSON as! NSData, encoding: NSUTF8StringEncoding))
//            finished(result: JSON as? [String: AnyObject], error: nil)
//            }) { (_, error) -> Void in
//                print(error)
//                finished(result: nil, error:error)
//                
////             "access_token" = "2.00q8z9CD022omS050a0c4e5dLrnGGC";
//        }
        
    
    }
    
    private func request (method: TYHNetworkMethod, urlString: String, params: [String: AnyObject], finished: TYHNetFinishCallBack) {
        
        //1.定义成功的回调
        let successCallBack:(NSURLSessionDataTask!, AnyObject!) -> Void = { (_, JSON) -> Void in
            if let result = JSON as? [String: AnyObject] {
                finished(result: result, error: nil)
            }else{
                print("没有数据 GET Request \(urlString)")
                
                
                finished(result: nil, error: TYHNetworkError.emptyDataError.error())
            }
            
        }
        
        //2. 定义失败的回调
        let failedCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
            print(error)
            
            finished(result: nil, error: error)
        }
        
        //3. 根据method 来选择调用的方法
        switch method {
        case.GET:
            GET(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        case.POST:
            POST(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        }
        
        
        
    }
    
    //上传图像
    private func uploadImage(urlString: String, image: UIImage, params: [String: AnyObject], finished: TYHNetFinishCallBack) {
        
        //1.定义成功的回调
        let successCallBack:(NSURLSessionDataTask!, AnyObject!) -> Void = { (_, JSON) -> Void in
            if let result = JSON as? [String: AnyObject] {
                finished(result: result, error: nil)
            }else{
                print("没有数据 \(urlString)")
                
                
                finished(result: nil, error: TYHNetworkError.emptyDataError.error())
            }
            
        }
        
        //2. 定义失败的回调
        let failedCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
            print(error)
            
            finished(result: nil, error: error)
        }
        
        
        
        POST(urlString, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
            
            let data = UIImagePNGRepresentation(image)
            
            formData.appendPartWithFileData(data, name: "pic", fileName: "XXX", mimeType: "application/octet-stream")
            
            }, success: successCallBack, failure: failedCallBack)
    
    }
    
    ///GET 请求
    private func requestGET(urlString: String, params: [String: AnyObject], finished: TYHNetFinishCallBack) {
        
        
        GET(urlString, parameters: params, success: { (_, JSON) -> Void in
            if let result = JSON as? [String: AnyObject] {
                finished(result: result, error: nil)
            }else{
                print("没有数据 GET Request \(urlString)")
                
                
                finished(result: nil, error: TYHNetworkError.emptyDataError.error())
            }
            
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    
    }
    
    
    
}






